<script setup>
import { getCategoryDetail } from '@/api/home'
import { imgSynthsis, editImgUpload, maskImgUpload, getImageByTaskId } from '@/api/painting'
import Toast from "@vant/weapp/dist/toast/toast";
import newLoading from '@/components/newLoading/index.vue';
import labourSelect from './child/labourSelect.vue';
import aiSelect from './child/aiSelect.vue';
import { usePaintingStore } from '@/store'
import { ref } from 'vue';
import { onLoad, onUnload } from '@dcloudio/uni-app';


const paintingStore = usePaintingStore()

// 页面携带参数
const queryItem = ref({})
// 查询详情信息
const queryInfo = ref({})


// 图片数量列表
const imgNumList = ref([])
// 消耗算力
const expendNum = ref(0)

const tabsCurrent = ref(0);
const loading = ref(false);
const loadingRef = ref(null);

const aiSelectRef = ref(null);
const labourSelectRef = ref(null);
const labourSelectInfo = ref({});

const queryData = ref({
    prompt: '',
    baseImageUrl: '',
    maskImageUrl: '',
    model: 'DOUBAO' // TYWX - DOUBAO
})
const taskId = ref('')

let timer = null

const imgNum = ref(1)


// 图片数量点击事件
function imgNumClick(e) {
    imgNum.value = e
}


function tabsChange(e) {
    if (e === 1) {
        return Toast.fail("功能即将开放！")
    }
    tabsCurrent.value = e
}

// 关闭loading事件
function loadingClose() {
    clearInterval(timer);
}


// 获取任务状态
async function getImageByTaskIdFn() {
    const res = await getImageByTaskId(taskId.value)
    if (res.data.state === 1) {
        clearInterval(timer);
        await loadingRef.value.completeLoading()
        res.data.modelTypeId = queryItem.value.modelTypeId
        uni.navigateTo({
            url: `/newEditionDraw/localRedrawing/detail/index?data=${JSON.stringify(res.data)}`
        })
    } else if (![3, 4].includes(res.data.state)) {
        clearInterval(timer);
        const errorMessage = res.data?.remark.split('失败原因：')[1]
        Toast.fail(errorMessage);
        loading.value = false
    }
}



// 任务提交
async function imgSynthsisFn() {
    paintingStore.setLocalRedrawingFn(queryData.value)
    try {
        const res = await imgSynthsis(queryData.value)
        taskId.value = res.data.taskId
        timer = setInterval(() => {
            getImageByTaskIdFn()
        }, 5000);
    } catch (error) {
        loading.value = false
    }
}

// 蒙版层图片上传
async function maskImgUploadFn() {
    const res = await maskImgUpload({
        orgImgUrl: queryData.value.baseImageUrl,
        maskType: 9,
        maskImg: labourSelectInfo.value.maskImageUrl,
    })
    queryData.value.maskImageUrl = res
}


// 上传原图
async function editImgUploadFn() {
    try {
        const res = await editImgUpload({
            type: 9,
            orgImg: labourSelectInfo.value.baseImageUrl
        })
        queryData.value.baseImageUrl = res.orgImgUrl
    } catch (error) {
        loading.value = false
    }
}


async function labourSelectFn() {
    const res = await labourSelectRef.value.createFn()
    labourSelectInfo.value = JSON.parse(JSON.stringify(res))
    queryData.value.prompt = res.prompt
    queryData.value.num = res.num
    await verifyFn()
    loading.value = true
    await editImgUploadFn()
    await maskImgUploadFn()
    imgSynthsisFn()
}

// 校验方法
function verifyFn() {
    return new Promise((resolve, reject) => {
        if (!labourSelectInfo.value.baseImageUrl) {
            Toast.fail("请上传原图！");
            return reject()
        }

        else if (!labourSelectInfo.value.maskImageUrl) {
            Toast.fail("未检测到涂抹区域！");
            return reject()
        }

        else if (!labourSelectInfo.value.prompt) {
            Toast.fail("请输入修改描述词");
            return reject()
        }

        resolve()
    })
}


async function startFn() {
    clearInterval(timer);
    switch (tabsCurrent.value) {
        case 0:
            labourSelectFn()
            break;
        case 1:
            break;
    }
}



// 获取分类详情
async function getCategoryDetailFn() {
    const res = await getCategoryDetail(queryItem.value.id)
    queryInfo.value = res.data
    dataConversion()
}


// 数据转换
function dataConversion() {
    queryInfo.value.categoryParam.forEach(item => {
        if (item.title === 'imgNum') {
            imgNumList.value = item.data[0].title.split(',')
            // queryData.value.num = imgNumList.value[0]
        }
        else if (item.title === 'expendNum') {
            expendNum.value = item.data[0].title
        }
    })
}

onUnload(() => {
    clearInterval(timer);
    loading.value = false
})


onLoad((e) => {
    if (e.item) {
        queryItem.value = JSON.parse(e.item)
    }
    getCategoryDetailFn()
})
</script>

<template>
    <div class='localRedrawing'>
        <NavBar :zIndex="5">{{ queryInfo?.title }}</NavBar>
        <div class="container">
            <div class="tabs">
                <div class="tab" :class="{ active: tabsCurrent === 0 }" @click="tabsChange(0)">手动选取</div>
                <div class="tab" :class="{ active: tabsCurrent === 1 }" @click="tabsChange(1)">智能选取</div>
            </div>

            <!-- 人工选取 -->
            <labourSelect ref="labourSelectRef" :imgNumList="imgNumList" v-if="tabsCurrent === 0"
                @imgNumClick="imgNumClick"></labourSelect>
            <!-- AI选取 -->
            <aiSelect ref="aiSelectRef" v-else></aiSelect>
        </div>
        <div class="footer">
            <div class="footer_placeholder"></div>
            <div class="footer_content">
                <myDrawButton :expendNum="expendNum * imgNum" @click="startFn">开始重绘</myDrawButton>
            </div>
        </div>
    </div>
    <newLoading ref="loadingRef" v-model="loading" :duration="10000" :label="['排队中，预计等待时间10秒钟']" @close="loadingClose">
    </newLoading>
    <van-toast id="van-toast" />
</template>

<style lang='scss' scoped>
.localRedrawing {
    .container {
        padding: 0 30rpx 30rpx;

        .tabs {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-top: 40rpx;

            .tab {
                box-sizing: border-box;
                width: 335rpx;
                height: 64rpx;
                line-height: 64rpx;
                border-radius: 32rpx;
                text-align: center;
                font-size: 30rpx;
                color: #C2C2C2;
                border: 2rpx solid transparent;

                &.active {
                    color: #83CD88;
                    border: 2rpx solid #83CD88;
                }
            }
        }
    }

    .footer {
        .footer_placeholder {
            height: 176rpx;
        }

        .footer_content {
            box-sizing: border-box;
            position: fixed;
            bottom: 0;
            left: 0;
            z-index: 2;
            width: 100%;
            height: 176rpx;
            background: #212142;
            padding: 28rpx 30rpx 0;
        }
    }
}
</style>